package com.iafe.servodroid;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class Controller implements OnSeekBarChangeListener, OnClickListener {

	private static Controller instance;
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	BluetoothSocket socket = null;
	OutputStream os;
	InputStream is;

	/***************************************************/
	private Controller() {
	}

	/***************************************************/
	public static Controller getInstance() {
		if (instance == null) {
			instance = new Controller();
		}
		return instance;
	}

	/***************************************************/
	@Override
	public void onProgressChanged(SeekBar seekBar, int value, boolean user) {
		MainActivity.getInstance().setAngle(value);
	}

	/***************************************************/
	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
	}

	/***************************************************/
	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		if (socket != null) {
			int val = MainActivity.getInstance().getAngleValue();
			try {
				os.write(val);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/***************************************************/
	@Override
	public void onClick(View v) {
		Button b = (Button) v;

		if (b.getText().equals("Connect")) {
			Set<BluetoothDevice> devs = getPairedDevices();
			BluetoothDevice linvorDevice = null;
			boolean present = false;
			for (BluetoothDevice dev : devs) {
				if (dev.getName().equals("linvor")) {
					present = true;
					linvorDevice = dev;
				}
			}
			Toast t;
			t = Toast.makeText(MainActivity.getInstance()
					.getApplicationContext(), "LINVOR "
					+ (present ? "" : "NOT ") + "Present", Toast.LENGTH_LONG);
			t.show();
			if (present) {
				Method m;
				try {
					m = linvorDevice.getClass().getMethod("createRfcommSocket",
							new Class[] { int.class });
					socket = (BluetoothSocket) m.invoke(linvorDevice, 1);
					socket.connect();
					os = socket.getOutputStream();
					// ir = new BufferedReader(new
					// InputStreamReader(socket.getInputStream()));
					is = socket.getInputStream();
					b.setText("Disconnect");
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		} else if (b.getText().equals("Send")) {
			try {
				int val = MainActivity.getInstance().getAngleValue();
				os.write(val);
				/*
				 * int c = is.read(); if (c != -1) { // String s = dummy +
				 * " c: " + String.valueOf(c) + ", v: " + String.valueOf(cl + ch
				 * * 0x100); TextView t = (TextView)
				 * MainActivity.getInstance().findViewById
				 * (R.id.responseTextView); t.setText(String.valueOf(c)); }
				 */
				/*
				 * int sentValue = (int) (640 + ((float) val) * 6.5f); String
				 * sentValueString = new
				 * DecimalFormat("0000").format(sentValue); int len =
				 * sentValueString.length(); for (int i = 0; i < len; i++) {
				 * os.write(sentValueString.charAt(len - i - 1)); try {
				 * Thread.sleep(20); } catch (InterruptedException e) {
				 * e.printStackTrace(); } }
				 */
				/*
				 * os.write('*'); os.write(val); int dummy = is.read(); int c =
				 * is.read(); int cl = is.read(); int ch = is.read(); if (cl !=
				 * -1 && ch != -1) { String s = dummy + " c: " +
				 * String.valueOf(c) + ", v: " + String.valueOf(cl + ch *
				 * 0x100); TextView t = (TextView)
				 * MainActivity.getInstance().findViewById
				 * (R.id.responseTextView); t.setText(s); }
				 */

			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (b.getText().equals("Disconnect")) {
			try {
				os.close();
				socket.close();
				socket = null;
				b.setText("Connect");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @return
	 *************************************************/
	public Set<BluetoothDevice> getPairedDevices() {
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		bluetoothAdapter.startDiscovery();
		Set<BluetoothDevice> pairedDevices = bluetoothAdapter
				.getBondedDevices();

		return pairedDevices;
	}
}
